package com.north.light.libpicselect.model;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import com.north.light.libpicselect.bean.LibMediaType;
import com.north.light.libpicselect.bean.LibPicInfo;
import com.north.light.libpicselect.bean.LibPicMediaCursorInfo;
import com.north.light.libpicselect.PicSelParamsBuilder;
import com.north.light.libpicselect.permission.LibPicPermissionCheck;
import com.north.light.libpicselect.permission.LibPicPermissionType;
import com.north.light.libpicselect.utils.LibMediaInfoUtils;
import com.north.light.libpicselect.utils.LibPicHandlerManager;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * create by lzt
 * data 2019/12/8
 * 图片选择库
 * Cursor获取数据
 */
public class LibPicSelectManager implements LibPicSelectApi {
    private static final String TAG = LibPicSelectManager.class.getName();
    private Context mContext;
    private volatile boolean isInit = false;
    private OnResultListener mCallBack;
    //是否显示gif
    private boolean isShowGif = false;
    //是否显示视频
    private boolean isShowVideo = false;
    //数据过滤参数
    private PicSelParamsBuilder mPicSelParams = new PicSelParamsBuilder();

    private static final class SingleHolder {
        static final LibPicSelectManager mInstance = new LibPicSelectManager();
    }

    public static LibPicSelectManager getInstance() {
        return SingleHolder.mInstance;
    }


    @Override
    public void init(Context context, InitCallBack callBack) {
        this.mContext = context.getApplicationContext();
        if (!LibPicPermissionCheck.getInstance().check(LibPicPermissionType.TYPE_EXTERNAL)) {
            if (callBack != null) {
                callBack.NoPermission();
            }
            return;
        }
        if (isInit) {
            if (callBack != null) {
                callBack.Success();
            }
            return;
        }
        isInit = true;
        if (callBack != null) {
            callBack.Success();
        }
    }

    /**
     * change by lzt  20200823增加是否显示视频的标识
     */
    @Override
    public void load(boolean isShowGif, boolean isShowVideo, PicSelParamsBuilder builder) {
        if (!isInit) {
            return;
        }
        this.isShowVideo = isShowVideo;
        this.isShowGif = isShowGif;
        if (builder != null) {
            this.mPicSelParams = builder;
        }
        if (LibPicHandlerManager.getInstance().getIOHandler() != null) {
            LibPicHandlerManager.getInstance().getIOHandler().removeCallbacksAndMessages(null);
            LibPicHandlerManager.getInstance().getIOHandler().post(loadRunnable);
        }
    }

    @Override
    public void release() {
        removeResultListener();
        if (LibPicHandlerManager.getInstance().getIOHandler() != null) {
            LibPicHandlerManager.getInstance().getIOHandler().removeCallbacksAndMessages(null);
        }
        isInit = false;
    }

    //加载数据的runnable
    private Runnable loadRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                loadDataByCursor();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 加载数据的函数
     * change by lzt 20200515 增加是否过滤gif的处理逻辑
     */
    private void loadDataByCursor() throws Exception {
        //获取图片数据
        Cursor picCursor = mContext.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        List<LibPicInfo> cacheRes = new ArrayList<>();
        while (picCursor.moveToNext()) {
            //获取图片的名称
            LibPicMediaCursorInfo picMediaCursorInfo = LibMediaInfoUtils.getCursorInfo(picCursor);
            if (TextUtils.isEmpty(picMediaCursorInfo.getName())) {
                //名字为空
                continue;
            }
            if (!isShowGif && (picMediaCursorInfo.getName().contains(".gif"))) {
                //不显示gif
                continue;
            }
            //获取图片的详细信息
            String name = picMediaCursorInfo.getName();
            int modifyTime = picMediaCursorInfo.getDate();
            String path = picMediaCursorInfo.getPath();
            long duration = picMediaCursorInfo.getDuration();
            int width = picMediaCursorInfo.getWidth();
            int height = picMediaCursorInfo.getHeight();
            String format = picMediaCursorInfo.getFormat();
            LibPicInfo info = new LibPicInfo(name, path, modifyTime,
                    duration, width, height, format, LibMediaType.PIC.getSource());
            cacheRes.add(info);
        }
        //获取视频数据
        if (isShowVideo) {
            Cursor videoCursor = mContext.getContentResolver().query(
                    MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
            while (videoCursor.moveToNext()) {
                //获取视频的名称
                LibPicMediaCursorInfo videoCursorInfo = LibMediaInfoUtils.getCursorInfo(videoCursor);
                if (TextUtils.isEmpty(videoCursorInfo.getName())) {
                    //名字为空
                    continue;
                }
                //获取图片的详细信息
                String name = videoCursorInfo.getName();
                int modifyTime = videoCursorInfo.getDate();
                String path = videoCursorInfo.getPath();
                long duration = videoCursorInfo.getDuration();
                int width = videoCursorInfo.getWidth();
                int height = videoCursorInfo.getHeight();
                String format = videoCursorInfo.getFormat();
                LibPicInfo info = new LibPicInfo(name, path, modifyTime,
                        duration, width, height, format, LibMediaType.VIDEO.getSource());
                cacheRes.add(info);
            }
        }
        //数据过滤-----------------------------------------------------------------------------
        //查询文件是否存在，获取文件相关信息
        List<LibPicInfo> result = new ArrayList<>();
        try {
            long st = System.currentTimeMillis();
            for (int i = 0; i < cacheRes.size(); i++) {
                File existFile = new File(cacheRes.get(i).getPath());
                if (!existFile.exists()) {
                    continue;
                }
                if (existFile.length() == 0) {
                    continue;
                }
                LibPicInfo cacheInfo = cacheRes.get(i);
                if (cacheInfo.getSource() == LibMediaType.VIDEO.getSource()) {
                    //视频
                    //校验视频长度是否符合
                    long videoDuration = cacheInfo.getDuration() / 1000;
                    long limitMin = mPicSelParams.getVideoMinDuration();
                    long limitMax = mPicSelParams.getVideoMaxDuration();
                    if (videoDuration < limitMin || videoDuration > limitMax) {
                        //数据不符合
                        continue;
                    }
                }
                result.add(cacheRes.get(i));
            }
            cacheRes.clear();
            Log.d(TAG, "总耗时： " + (System.currentTimeMillis() - st));
        } catch (Exception e) {
            Log.d(TAG, "处理文件错误:\n" + e.getMessage());
        }
        //统计目录下文件个数------------------------------------------
        Map<String, Long> directoryCountMap = new HashMap<>();
        for (int j = 0; j < result.size(); j++) {
            String directory = result.get(j).getDirectory();
            if (!TextUtils.isEmpty(directory)) {
                Long directoryCount = directoryCountMap.get(directory);
                directoryCountMap.put(directory, directoryCount == null ? 1 : directoryCount + 1);
            }
        }
        for (LibPicInfo info : result) {
            if (!TextUtils.isEmpty(info.getDirectory()) && directoryCountMap.get(info.getDirectory()) != null) {
                String directory = info.getDirectory();
                if (!TextUtils.isEmpty(directory)) {
                    Long directoryCount = directoryCountMap.get(directory);
                    if (directoryCount != null) {
                        info.setDirectoryCount(directoryCount);
                    }
                }
            }
        }
        //最后的结果-----------------------------------------------------------
        Collections.sort(result, new Comparator<LibPicInfo>() {
            @Override
            public int compare(LibPicInfo o1, LibPicInfo o2) {
                return o2.getDate() - o1.getDate();
            }
        });
        if (mCallBack != null) {
            mCallBack.Data(result);
        }
        //过滤的结果-目录分级----------------------------------------------------------
        Map<String, List<LibPicInfo>> filterMap = new HashMap<>();
        for (int i = 0; i < result.size(); i++) {
            String directoryName = result.get(i).getDirectory();
            if (!TextUtils.isEmpty(directoryName)) {
                List<LibPicInfo> cahce = filterMap.get(directoryName);
                if (cahce != null) {
                    cahce.add(result.get(i));
                } else {
                    cahce = new ArrayList<>();
                    cahce.add(result.get(i));
                }
                filterMap.put(directoryName, cahce);
            }
        }
        //修改时间排序-----------------------------------------------------------
        for (Map.Entry<String, List<LibPicInfo>> arg : filterMap.entrySet()) {
            Collections.sort(arg.getValue(), new Comparator<LibPicInfo>() {
                @Override
                public int compare(LibPicInfo o1, LibPicInfo o2) {
                    return o2.getDate() - o1.getDate();
                }
            });
        }
        if (mCallBack != null) {
            mCallBack.FilterData(filterMap);
        }
    }


    //结果回调
    public interface OnResultListener {
        void Data(List<LibPicInfo> result);//没有过滤的，是全部的结果

        void FilterData(Map<String, List<LibPicInfo>> filterMap);//过滤了的结果 key为目录，value为该目录下的数据
    }

    public void setOnResultListener(OnResultListener onResultListener) {
        this.mCallBack = onResultListener;
    }

    private void removeResultListener() {
        this.mCallBack = null;
    }

}
